import re
import server
import socket
import threading
import chat_list
import SocketServer

from chat import WndChat

global tcpserver
global server_thread
global PORT
global HOST

tcpserver = None

HOST, PORT = "0.0.0.0", 8001

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        print "Request from " + self.client_address[0]
        
        data = self.request.recv(1024)
        
        # Discriminate between cases
        if data == "": return
        
        rep = re.compile('/([^ ]+) ([^ ]+)')
        req = rep.match(data)
        if req != None:
            action = req.group(1)
            
            if action == 'open':
                username = req.group(2)

                chat = chat_list.search(username)
                if chat == None:
                    chat = WndChat(None, username, self.client_address[0], False, self.request)
                else:
                    chat.socket = self.request
                
                chat.status = True
                
                self.request.send("/ack " + server.username)
                chat.push_status("Connection established.")
        
        while (chat.status):
            data = self.request.recv(1024)
            if data == "": return
            
            req = rep.match(data)
            if req != None:
                action = req.group(1)
                
                if action == 'close':
                    self.request.close()
                    chat.push_status(username + " has left the conversation.")
                    chat.status = False
                    #chat._builder.get_object("txt_chat_message").set_sensitive(False)
                
            else:
                print "Server receiving data..."
                chat.inject_data(data)

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

        
def start():
    global tcpserver
    global server_thread

    try:
        tcpserver = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
        
    except Exception as ex:
        return ex.strerror
        
    else:
        ip, port = tcpserver.server_address

        server_thread = threading.Thread(target=tcpserver.serve_forever)
        server_thread.setDaemon(True)
        server_thread.start()
        
        return None
    

def stop():
    global tcpserver
    global server_thread

    if tcpserver == None: return
    
    tcpserver.socket.close()
    tcpserver.shutdown()
    
    server_thread.join()
